package la.renzhen.rtpt.admin.boot.starter.consul;

import com.ecwid.consul.v1.ConsulClient;
import la.renzhen.rtpt.admin.boot.conditional.ConditionalOnPrefixProperty;
import la.renzhen.rtpt.admin.boot.starter.CenterServerAutoConfigruation;
import la.renzhen.rtpt.admin.source.CenterConfigurationSource;
import la.renzhen.rtpt.admin.source.consul.ConsulCenterConfigurationSource;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 16/05/2018 7:31 PM
 */
@Configuration
@ConditionalOnMissingBean(CenterConfigurationSource.class)
@AutoConfigureBefore(CenterServerAutoConfigruation.class)
@EnableConfigurationProperties(ConsulProperties.class)
@ConditionalOnPrefixProperty("rtpt.admin.consul")
public class ConsulSourceAutoConfiguration {

    @Bean
    @ConditionalOnProperty("rtpt.admin.consul.address")
    public CenterConfigurationSource consulConfigSource(ConsulProperties config) throws SQLException {
        ConsulClient consulClient = new ConsulClient(config.getAddress());
        return new ConsulCenterConfigurationSource(consulClient, config.getModule());
    }

    @Bean
    @ConditionalOnBean(ConsulClient.class)
    @ConditionalOnMissingBean(CenterConfigurationSource.class)
    public CenterConfigurationSource consulClientConfigSource(ConsulClient consulClient, ConsulProperties config) {
        return new ConsulCenterConfigurationSource(consulClient, config.getModule());
    }

    @Bean
    @ConditionalOnMissingBean({ConsulClient.class, CenterConfigurationSource.class})
    public CenterConfigurationSource defConsulConfigSource(ConsulProperties config) {
        return new ConsulCenterConfigurationSource(new ConsulClient(config.getAddress()), config.getModule());
    }

}
